package service

import (
	ClickHouse "gin/database"
	"gin/model"
	"gin/types"
	"strings"
)

type Department struct {
}

type DepartmentListCount struct {
	Id       int64         `json:"id" gorm:"column:id"`
	Name     string        `json:"name" gorm:"column:name"`
	Type     string        `json:"type" gorm:"-"`
	TenantId int64         `json:"tenant_id" gorm:"column:tenant_id"`
	ParentId uint64        `json:"parent_id" gorm:"column:parent_id"`
	Count    uint64        `json:"count" gorm:"-"`
	UserId   uint64        `json:"user_id" gorm:"-"`
	Roles    []interface{} `json:"roles" gorm:"-"`
}

type DepartmentListCountMultiDepartmentUser struct {
	Id       uint64 `json:"id" gorm:"column:id"`
	Name     string `json:"name" gorm:"column:name"`
	Type     string `json:"type" gorm:"-"`
	TenantId uint64 `json:"tenant_id" gorm:"column:tenant_id"`
	ParentId uint64 `json:"parent_id" gorm:"column:parent_id"`
	Count    uint64 `json:"count" gorm:"-"`
	UserId   uint64 `json:"user_id" gorm:"-"`
	Role     string `json:"role" gorm:"-"`
}

// getDepartmentList 查询部门信息
func (d *Department) getDepartmentList(tenantId int64, where interface{}) (departmentList []model.Department, err error) {
	query := ClickHouse.DB.Model(&model.Department{})
	if tenantId > 0 {
		query.Where("tenant_id = ?", tenantId)
	}
	if where != nil {
		query.Where(where)
	}
	// 通过租户ID获取部门列表
	err = query.
		Find(&departmentList).Error
	return
}

// getUserDepartmentList 查询用户指定角色的部门信息
func (d *Department) getUserDepartmentList(userId int64, tenantId int64, roleCode string) (departmentList []model.TenantUser, err error) {
	dbr := ClickHouse.DB.Model(&model.TenantUser{}).
		Joins("JOIN role on tenant_user.role_id = role.id").
		Where("user_id = ?", userId).
		Where("tenant_id = ?", tenantId)
	if roleCode != "" {
		dbr.Where("role.code = ?", roleCode)
	}
	err = dbr.Find(&departmentList).Error
	return
}

// DeleteCheck 部门删除检查
func (d *Department) DeleteCheck(departmentIdList []int64) (res types.DepartmentDeleteCheckRes, err error) {
	var departmentIdListHasTask []int64
	err = ClickHouse.DB.Model(&model.Task{}).
		Where("department_id in ?", departmentIdList).
		Group("department_id").
		Pluck("department_id", &departmentIdListHasTask).Error
	if err != nil {
		return
	}
	var departmentHasTaskMap = make(map[int64]bool, len(departmentIdListHasTask))
	for _, ha := range departmentIdListHasTask {
		departmentHasTaskMap[ha] = true
	}

	var departmentIdListHasUser []int64
	err = ClickHouse.DB.Model(&model.TenantUser{}).
		Where("department_id in ?", departmentIdList).
		Group("department_id").
		Pluck("department_id", &departmentIdListHasUser).Error

	if err != nil {
		return
	}
	var departmentHasUserMap = make(map[int64]bool, len(departmentIdListHasUser))
	for _, ha := range departmentIdListHasUser {
		departmentHasUserMap[ha] = true
	}

	res = make(types.DepartmentDeleteCheckRes, 0)
	for _, departmentId := range departmentIdList {
		res[departmentId] = true
		// 是否有任务
		if _, ok := departmentHasTaskMap[departmentId]; ok {
			res[departmentId] = false
			continue
		}
		// 是否有用户
		if _, ok := departmentHasUserMap[departmentId]; ok {
			res[departmentId] = false
			continue
		}
	}
	return
}

// GetDepartmentListStepCategoryIdList 解析出部门里的分类id
func (d *Department) GetDepartmentListStepCategoryIdList(departmentList []model.Department) (res []int64, err error) {
	var existCheck = make(map[int64]bool)
	for _, department := range departmentList {
		if department.StepCategoryIds == "" {
			continue
		}
		for _, s := range strings.Split(department.StepCategoryIds, ",") {
			si := IntVal(s)
			if si <= 0 {
				continue
			}
			if _, ok := existCheck[si]; ok {
				continue
			}
			existCheck[si] = true
			res = append(res, si)
		}
	}
	return
}

// GetUserDepartmentStepCategoryIdList 查询用户部门环节id
func (d *Department) GetUserDepartmentStepCategoryIdList(tenantId, userId int64) (res []int64, err error) {
	var dl []model.Department
	dbr := ClickHouse.DB.Model(&model.TenantUser{}).
		Joins("JOIN department on tenant_user.department_id = department.id").
		Where("user_id = ?", userId).
		Where("tenant_id = ?", tenantId).Select("department.*")
	err = dbr.Find(&dl).Error
	if err != nil || len(dl) == 0 {
		return
	}
	return d.GetDepartmentListStepCategoryIdList(dl)
}

// getUserDepartmentListInfo 查询用户部门信息
func (d *Department) getUserDepartmentListInfo(userId int64, tenantId int64, roleCodeList []string) (departmentList []model.Department, err error) {
	err = ClickHouse.DB.Model(&model.Department{}).
		Where("id in (select department_id from tenant_user join role on role.id = tenant_user.role_id where tenant_user.tenant_id = ? and tenant_user.user_id = ? and role.code in ?)", tenantId, userId, roleCodeList).
		Find(&departmentList).Error
	return
}

func (d *Department) GetDepartment(where interface{}) (res model.Department, err error) {
	err = ClickHouse.DB.Model(&model.Department{}).Where(where).Find(&res).Error
	return
}
